package com.katze.boot.plugins.security.filter;

import com.katze.boot.plugins.redis.service.CacheService;
import com.katze.boot.plugins.security.JwtTokenProvider;
import com.katze.common.ResponseStatus;
import com.katze.common.http.HttpUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * SFTP文件下载进度过滤器
 */
public class DownloadProgressFilter extends OncePerRequestFilter implements IPathMatcher {
    private static final Logger log = LoggerFactory.getLogger(DownloadProgressFilter.class);

    private final OrRequestMatcher orRequestMatcher;
    private final String[] patterns = new String[]{"/sftp/progress"};

    @Lazy
    @Autowired
    private CacheService cacheService;

    public DownloadProgressFilter() {
        this.orRequestMatcher = new OrRequestMatcher(matchers());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (orRequestMatcher.matches(request)) {
            // 在这里添加自定义逻辑
            if (log.isDebugEnabled()) {
                log.debug("Progress URL filter executed for {}", request.getRequestURI());
            }
            // 请求来源地址
            String token = request.getParameter(TOKEN_NAME);
            if (token != null) {
                ResponseStatus status = JwtTokenProvider.verify(token, jwt -> {
                    String username = jwt.getClaim("username").asString();
                    String tokenCache = cacheService.getToken(username);
                    if (StringUtils.isBlank(tokenCache)) {
                        // 认证失败，token失效或被强制下线
                        return ResponseStatus.TOKEN_INVALID;
                    } else if (tokenCache.contains("@") && !HttpUtils.getRemoteAddress().equals(tokenCache.split("@")[1])) {
                        // 认证失败,token绑定ip与当前发起请求的ip不符合
                        return ResponseStatus.TOKEN_NOT_MATCH_IP;
                    } else {
                        return ResponseStatus.OK;
                    }
                });
                if (status == ResponseStatus.OK) {
                    chain.doFilter(request, response);
                } else {
                    response.sendError(status.value(), status.note());
                }
            } else {
                response.setStatus(ResponseStatus.FORBIDDEN.value());
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"code\":" + ResponseStatus.FORBIDDEN.value() + ",\"type\":\"error\",\"message\":\"禁止未授权访问\"}");
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public String[] getPatterns() {
        return patterns;
    }
}
